package com.gwcm.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gwcm.common.annotation.UserId;
import com.gwcm.exception.BusinessException;
import com.gwcm.model.dto.login.DoLoginRequest;
import com.gwcm.model.dto.register.EmailRegisterRequest;
import com.gwcm.model.dto.user.UserDeleteRequest;
import com.gwcm.model.dto.user.UserQueryRequest;
import com.gwcm.model.dto.user.UserRoleAddRequest;
import com.gwcm.model.entity.User;
import com.gwcm.model.entity.UserRole;
import com.gwcm.model.vo.CaptchaImageVo;
import com.gwcm.model.vo.TokenIdVo;
import com.gwcm.model.vo.UserVo;
import com.gwcm.security.domain.AuthUser;
import com.gwcm.service.ILoginService;
import com.gwcm.service.IMenuService;
import com.gwcm.service.IUserService;
import com.gwcm.util.JwtUtil;
import com.gwcm.util.ServletUtils;
import com.yhz.commonutil.common.BaseResponse;
import com.yhz.commonutil.common.ErrorCode;
import com.yhz.commonutil.common.ResultUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Api(tags = "用户接口")
public class UserController {
    @Resource
    public IUserService userService;
    @Resource
    private ILoginService loginService;
    @Resource
    private IMenuService menuService;
    @Resource
    private JwtUtil jwtUtil;
    @ApiOperation("分页查询用户接口")
    @PreAuthorize("hasAuthority('system:user:list')")
    @PostMapping("/page")
    public BaseResponse<IPage<UserVo>> pageModuleTopic(@RequestBody UserQueryRequest userQueryRequest) throws BusinessException {
        IPage<UserVo> userVoIPage = userService.pageList(userQueryRequest);
        return ResultUtils.success(userVoIPage);
    }

    @ApiOperation("用户登录接口")
    @PostMapping("/login")
    public BaseResponse<String> doLogin(@Valid @RequestBody DoLoginRequest doLoginRequest, String rememberMe, HttpServletRequest request, HttpServletResponse response) {
        String token = loginService.doLogin(doLoginRequest, request, response);

        return ResultUtils.success(token);
    }

    @ApiOperation("获取登录用户信息")
    @GetMapping("/getInfo")
    public BaseResponse getInfo() throws Exception {
        AuthUser authUser = jwtUtil.getAuthUser(ServletUtils.getRequest());
        System.out.println(ServletUtils.getRequest());
        User user = authUser.getUser();
        Map<String, Object> data = new HashMap<>();
        data.put("id",user.getId());
        data.put("username",user.getUsername());
        data.put("nickname",user.getNickname());
        data.put("head_url",user.getHeadUrl());
        data.put("roles", userService.selectUserRoleGroup(user));
        data.put("authorities",menuService.selectMenuPermsByUserId(user.getId()));
        return ResultUtils.success(data);
    }

    @ApiOperation("用户注销登录接口")
    @GetMapping("/logout")
    public BaseResponse doLogout() {
        loginService.doLogout();
        return ResultUtils.success();
    }

    @ApiOperation("邮箱验证码发送接口")
    @GetMapping("/email/send")
    public BaseResponse mailSend(@RequestParam("email") String email) {
        loginService.mailSend(email);
        return ResultUtils.success();
    }

    @ApiOperation("邮箱注册接口")
    @PostMapping("/register/email")
    public BaseResponse register(@Valid @RequestBody EmailRegisterRequest registerDto) {
        loginService.emailRegister(registerDto);
        return ResultUtils.success();
    }
    @GetMapping("/captchaImage")
    @ApiOperation(value = "获取验证码（数学表达式）")
    public BaseResponse captchaImage() {
        CaptchaImageVo captchaImageVo = loginService.createCaptchImage();
        return ResultUtils.success(captchaImageVo);
    }
    @ApiOperation("通过ID查询user")
    @GetMapping("/{userId}")
    public BaseResponse getById(@PathVariable("userId") Long userId){
        return ResultUtils.success(userService.selectUserById(userId));
    }

//    @ApiOperation("通过username查询user")
//    @GetMapping("/{username}")
//    public BaseResponse getByUsername(@PathVariable("username") String username){
//        return ResultUtils.success(userService.selectUserByUsername(username));
//    }

    @ApiOperation("修改用户")
    @PutMapping
    public BaseResponse edit(@RequestBody User user){
        int count = userService.updateUser(user);
        return count > 0 ? ResultUtils.success("修改用户成功") : ResultUtils.error(ErrorCode.UPDATE_ERROR);
    }

    @ApiOperation("根据ID删除用户")
    @PostMapping("/delete")
    public BaseResponse deleteRole(@RequestBody UserDeleteRequest userDeleteRequest){
        User user = new User();
        BeanUtils.copyProperties(userDeleteRequest, user);
        boolean delete = userService.removeById(user);
        if(!delete){
            throw new BusinessException(ErrorCode.DELETE_ERROR);
        }
        return ResultUtils.success();
    }

    @ApiOperation("为用户分配角色")
    @PostMapping("/authRole")
    public BaseResponse insertAuthRole(@RequestBody UserRoleAddRequest userRoleAddRequest){
//        UserRole userRole = new UserRole();
//        BeanUtils.copyProperties(userRoleAddRequest, userRole);
        userService.insertUserAuth(userRoleAddRequest.getUserId(),userRoleAddRequest.getRoleIds());
        return ResultUtils.success("分配角色成功");
    }

    @ApiOperation("获取动态路由/SideBar菜单")
    @GetMapping("/getRouters")
    public BaseResponse getRouters(@UserId Long userId){
        return ResultUtils.success(menuService.getRouters(userId));
    }
}
